var wxUtil = require('../../../utils/wxUtil.js');
var util = require('../../../utils/util.js');
var ajax = require('../../../utils/ajax.js');
var common = require('../../../utils/common.js');
var PageBase = require('../../../common/PageBase.js');
var WxParse = require('../../../utils/wxParse/wxParse.js');
var app = getApp();

Page(common.extendPage(PageBase, {
  data: {
    dataLoaded: false,
    myHidden: true,
    submiting: false,
    hideDel: false,
    isNotAny: false,
    addrList: [],
    addressId: '',
    name: '',
    tel: '',
    addr: '',
    province: '',
    city: '',
    county: '',
    provinceId: '',
    cityId: '',
    countyId: '',
    value: [0, 0, 0],
    values: [0, 0, 0],
    provinces: [],
    citys: [],
    countys: [],
    province_id: [],
    city_id: [],
    county_id: [],
    province_name: [],
    city_name: [],
    county_name: [],
  },
  onLoad: function (options) {

    common.initApp({
      loginSuc: () => {
        this._initAddr('isOnload');
        this.provinces();
        this.citys(1);
        this.countys(2)
      }
    });
    // this._orderOptions = options.orderOptions;
    
  },
  /**
   * 省市区开
   */
  _open: function (e) {
    var formId = e.detail.formId;
    this.setData({
      condition: true
    })
    common.submitForm(formId);
  },
  /**
   * 省市区关闭
   */
  _close: function (e) {
    this.setData({
      condition: false
    })
    if (e) {
      var formId = e.detail.formId;
      common.submitForm(formId);
    }
  },
  /**
   * 初始化地址列表
   */
  _initAddr: function (isOnload) {
    var _self = this;
    ajax.G({
      url: 'm=user&c=address',
      data: {
        uid: app.getUid(),
        size: 999
      },
      success: (res) => {
          //debugger;
          var result = res.data;
          _self.setData({
            addrList: result.item,
            dataLoaded: true
          })
      }
    });

  },
  /**
   * 地址保存 
   */
  _submit: function (e) {
    var _self = this;
    var formId = e.detail.formId;

    if (_self.validInput(e.detail.value)) {
      _self.setData({
        dataLoaded: false,
        name: e.detail.value.userName,
        tel: e.detail.value.telPhone.trim(),
        addr: e.detail.value.addr,
        submiting: true
      })
      var addressId = this.data.addressId;
      var addrList = this.data.addrList;
      if (this.data.addressId != '') {
        _self.handleAddr(addressId);
      } else {
        if (_self.data.addrList.length == 0) {
          _self.handleAddr('', 1, function () {
            _self._goPrevPage();
          });
        } else {
          _self.handleAddr();
        }
      }

      /*
      ** 这个是旧数据,优化后,不需要,留在这里的目的是为了溯源
      ***
      // if (_self.data.goodsId != '') {
      //     setTimeout(function() {
      //         var orderOptions = JSON.parse(_self._orderOptions);
      //         var url = '/pages/confirmOrder/confirmOrder?addressId=' + _self.data.addressId;

      //         Object.keys(orderOptions).forEach(function(key) {
      //             url += '&' + key + '=' + orderOptions[key];
      //         });
      //         wx.redirectTo({
      //             url
      //         });
      //     }, 500)
      // }
      **/

      if (_self.data.condition) {
        _self._close();
      }
    }
    _self.setData({
      dataLoaded: true
    })
    common.submitForm(formId);
  },
  /**
   * 绑定表单输入
   */
  _setName: function (e) {
    var _self = this;
    var name = e.detail.value;
    _self.setData({
      name: name
    })
  },
  _setTel: function (e) {
    var _self = this;
    var tel = e.detail.value;
    _self.setData({
      tel: tel
    })
  },
  proCityCounty: function (e) {
    this.setData({
      proCityCounty: e.detail.value
    })
  },
  _setAddr: function (e) {
    var _self = this;
    var addr = e.detail.value;
    _self.setData({
      addr: addr
    })
  },


  //授权微信绑定手机号
  _loginByPhoneNumber(e) {
    //debugger;
    var {
      errMsg,
      iv,
      encryptedData
     } = e.detail;
    // var {
    //   nickName,
    //   avatarUrl
    //     } = app.globalData.userInfo || {};

    if (!/:ok$/.test(errMsg)) {
      if (errMsg == 'getPhoneNumber:fail user deny') {
        return false;
      } else {
        util.showWarn(errMsg);
      }
      return;
    };
    this._add(e);
    ajax.P({
      url: 'm=user&c=index&a=info',
      data: {
        uid: app.getUid(),
        iv,
        encryptedData
      },
      success: (data) => {
        //debugger;
      }
    });
  },


  /**
   * 添加地址
   */
  _add: function (evt) {
    //debugger;
    var _self = this;
    //var formId = evt.detail.formId;
    (function (callBack) {
      _self.provinces(function () {
        _self.citys(1, function () {
          _self.countys(2, function () {
            callBack && callBack();
          });
        });
      });
    })(
      function () {
        _self.setData({
          myHidden: false,
          addressId: '',
          name: '',
          tel: '',
          addr: '',
          hideDel: true,
          value: [0, 0, 0],
          values: [0, 0, 0],
          province: '北京市',
          city: '市辖区',
          county: '东城区',
          provinceId: '',
          cityId: '1',
          countyId: '2'
        })
      })
    //common.submitForm(formId);
  },
  /**
   * 取消添加地址
   */
  _cancel: function (e) {
    var _self = this;
    //var formId = e.detail.formId;
    _self.setData({
      myHidden: true
    })
    if (_self.data.condition) {
      _self._close();
    }
    //common.submitForm(formId);
  },
  /**
   * 编辑地址
   */
  _edit: function (e) {
    //debugger;
    var index = parseInt(e.currentTarget.dataset.index);
    var addrList = this.data.addrList;
    var formId = e.detail.formId;
    var _self = this;

    (function (callBack) {
      _self.setData({
        myHidden: false,
        hideDel: false,
        addressId: addrList[index].id,
        name: addrList[index].name,
        tel: addrList[index].tel,
        addr: addrList[index].address,
        value: [0, 0, 0],
        values: [0, 0, 0],
        dataLoaded: false
      })
      _self.provinces(function () {
        _self.citys(1, function () {
          _self.countys(2, function () {
            callBack && callBack();
          });
        });
      });
    })(
      function () {
        _self.setData({
          province: addrList[index].provinceName,
          city: addrList[index].cityName,
          county: addrList[index].districtName,
          provinceId: addrList[index].provinceId,
          cityId: addrList[index].cityId,
          countyId: addrList[index].districtId,
          dataLoaded: true
        })
      })
    common.submitForm(formId);
  },
  /**
   * 删除地址
   */
  _del: function (e) {
    var _self = this;
    var formId = e.detail.formId;
    _self.setData({
      dataLoaded: false,
    })
    ajax.G({
      url: 'm=user&c=address&a=del',
      data: {
        uid: app.getUid(),
        id: _self.data.addressId
      },
      success: (res) => {
        _self.setData({
          myHidden: true
        })
        _self._initAddr();
      }
    });


    if (_self.data.condition) {
      _self._close();
    }
    //common.submitForm(formId);
  },
  /**
   * 设置默认值
   */
  _selectDefault: function (e) {
    var _self = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var addrList = this.data.addrList;
    var formId = e.detail.formId;
    _self.setData({
      addressId: addrList[index].id,
    })
    ajax.G(
      '/openapi/CAddress/setDefault', {
        id: _self.data.addressId
      },
      function (data) {
        _self._initAddr();
      })
    //common.submitForm(formId);
  },
  /**
   * 请求省数据
   */
  provinces: function (callBack) {
    this.setData({
      province_id: []
    })
    var _self = this;
    ajax.G({
      url: 'm=index&c=common&a=city&id=0',
      data: {},
      success: (data) => {
        //debugger;
        var province_id = _self.data.province_id;
        var province_name = _self.data.province_name;
        var d = data.data;

        _self.setData({
          provinces: d
        })
        for (var i = 0; i < _self.data.provinces.length; i++) {
          province_id.push(_self.data.provinces[i].id);
          province_name.push(_self.data.provinces[i].name);
        }
        _self.setData({
          province_id: province_id,
          province_name: province_name,
          province: province_name[0],
          provinceId: province_id[0]
        });

        callBack && callBack();

      }
    });


  },
  /**
   * 请求市数据
   */
  citys: function (province_id, callBack) {
    this.setData({
      city_id: []
    })
    var _self = this;

    ajax.G({
      url: 'm=index&c=common&a=city',
      data: {
        id: province_id
      },
      success: (data) => {
        var city_id = _self.data.city_id;
        var city_name = _self.data.city_name;
        var city = _self.data.city;
        var d = data.data;

        _self.setData({
          citys: d
        })
        for (var i = 0; i < _self.data.citys.length; i++) {
          city_id.push(_self.data.citys[i].id);
          city_name.push(_self.data.citys[i].name);
        }
        _self.setData({
          city_id: city_id,
          city_name: city_name,
          city: city_name[0],
          cityId: city_id[0]
        });

        callBack && callBack();

      }
    });



  },

  /**
   * 请求区数据
   */
  countys: function (city_id, callBack) {

    this.setData({
      county_id: []
    })
    var _self = this;

    ajax.G({
      url: 'm=index&c=common&a=city',
      data: {
        id: city_id
      },
      success: (data) => {
        var county_id = _self.data.county_id;
        var county_name = _self.data.county_name;
        var d = data.data;

        _self.setData({
          countys: d
        })
        for (var i = 0; i < _self.data.countys.length; i++) {
          county_id.push(_self.data.countys[i].id);
          county_name.push(_self.data.countys[i].name)
        }
        _self.setData({
          county_id: county_id,
          county_name: county_name,
          county: county_name[0],
          countyId: county_id[0]
        });

        callBack && callBack();

      }
    });



  },
  /**
   * 切换省市区
   */
  bindChange: function (e) {
    var val = e.detail.value;
    var t = this.data.values;
    if (val[0] != t[0]) {
      var _self = this;
      var province_id = this.data.province_id;
      var province = this.data.province_name[val[0]];
      var provinceId = province_id[val[0]]
      this.setData({
        city_id: [],
        city_name: [],
        city: "",
        county_id: [],
        county_name: [],
        county: ""
      });

      ajax.G({
        url: 'm=index&c=common&a=city',
        data: {
          id: provinceId
        },
        success: (data) => {
          // success
          var city_id = _self.data.city_id;
          var city_name = _self.data.city_name;
          var d = data.data;
          _self.setData({
            citys: d
          })
          for (var i = 0; i < _self.data.citys.length; i++) {
            city_id.push(_self.data.citys[i].id);
            city_name.push(_self.data.citys[i].name);
          }
          _self.setData({
            city_id: city_id,
            city_name: city_name,
            city: city_name[0],
            cityId: city_id[0]
          });
          _self.countys(provinceId, city_id[0])
        }
      });


      this.setData({
        province: this.data.province_name[val[0]],
        city: this.data.city_name[val[1]],
        county: this.data.county_name[val[2]],
        provinceId: this.data.province_id[val[0]],
        cityId: this.data.cityId,
        countyId: this.data.countyId,
        values: val,
        value: [val[0], 0, 0]
      })
      return;
    }
    if (val[1] != t[1]) {
      var _self = this;
      var province_id = this.data.province_id[val[0]];
      var province = this.data.province_name[val[0]];
      var city_id = _self.data.city_id[val[1]];
      var city = _self.data.city_name[val[1]];
      this.setData({
        county_id: [],
        county_name: [],
        county: ""
      })


      ajax.G({
        url: 'm=index&c=common&a=city',
        data: {
          id: city_id
        },
        success: (data) => {

          // success
          var county_id = _self.data.county_id;
          var county_name = _self.data.county_name;
          var d = data.data;
          _self.setData({
            countys: d
          })
          for (var i = 0; i < _self.data.countys.length; i++) {
            county_id.push(_self.data.countys[i].id);
            county_name.push(_self.data.countys[i].name);
          }
          _self.setData({
            county_id: county_id,
            county_name: county_name,
            county: county_name[0],
            countyId: county_id[0]
          });

        }
      });

      this.setData({
        city: this.data.city_name[val[1]],
        cityId: this.data.city_id[val[1]],
        county: this.data.county_name[val[2]],
        countyId: this.data.county_id[val[2]],
        values: val,
        value: [val[0], val[1], 0]
      })
      return;
    }
    if (val[2] != t[2]) {
      this.setData({
        county: this.data.county_name[val[2]],
        countyId: this.data.county_id[val[2]],
        values: val,
        value: [val[0], val[1], val[2]]
      })
      return;
    }
  },

  handleAddr: function (addressId, isDefault, cb) {
    //debugger;
    var _self = this;
    if (typeof (addressId) == "undefined"){
      addressId = "";
    }
    ajax.P({
      url: 'm=user&c=address&a=add',
      data: {
        uid: app.getUid(),
        name: this.data.name,
        tel: this.data.tel,
        address: this.data.addr,
        province: this.data.province,
        city: this.data.city,
        county: this.data.county,
        id: addressId
        //isDefault: isDefault
      },
      success: (data) => {
        //debugger;

        _self.setData({
          addressId: data.data.id,
          myHidden: true,
          submiting: false
        })
        _self._initAddr();
        util.alert('保存成功', function () {
          cb && cb();
        });

      }
    });



  },
  /**
   * 验证输入消息
   */
  validInput: function (inputValue) {
    var {
            userName,
      telPhone,
      addr
        } = inputValue || {};

    if (userName.length == 0) {
      util.alert('请输入您的收货人姓名');
      return false;
    } else if (userName.length > 20) {
      util.alert('收货人长度不能超过20位');
      return false;
    } else if (telPhone.length == 0) {
      util.alert('请输入您的手机号');
      return false;
    } else if (!/^1\d{10}$/.test(telPhone.trim())) {
      util.alert('您输入的手机号格式不正确');
      return false;
    } else if (addr.length == 0) {
      util.alert('请输入您的详细地址');
      return false;

    } else if (addr.length > 100) {
      util.alert('您输入的地址长度不能超过100位');
      return false;
    }
    return true;
  },

  showZanTopTips(content = '', options = {}) {
    var zanTopTips = this.data.zanTopTips || {};
    // 如果已经有一个计时器在了，就清理掉先
    if (zanTopTips.timer) {
      clearTimeout(zanTopTips.timer);
      zanTopTips.timer = undefined;
    }

    if (typeof options === 'number') {
      options = {
        duration: options
      };
    }

    // options参数默认参数扩展
    options = Object.assign({
      duration: 1000
    }, options);

    // 设置定时器，定时关闭topTips
    var timer = setTimeout(() => {
      this.setData({
        'zanTopTips.show': false,
        'zanTopTips.timer': undefined
      });
    }, options.duration);

    // 展示出topTips
    this.setData({
      zanTopTips: {
        show: true,
        content,
        options,
        timer
      }
    });
  },
  /**
   * 页面跳转
   */
  _jump: function (evt) {
    common.jump(evt);
  },
  /**
   * 设置上一个页面的数据,并跳转到上一个页面
   */
  _goPrevPage: function () {
    var _self = this;
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    console.log(prevPage);
    prevPage.setData({
      optionAddrId: _self.data.addressId,
      myIf: false
    })
    if (prevPage.route != 'pages/my/index'){
      wx.navigateBack({
        delta: 1
      });
    }

  }
}))